package utils

import (
	"context"
	"fmt"
	"github.com/jordan-wright/email"
	"github.com/mojocn/base64Captcha"
	"log"
	"net/smtp"
	"project05_web/src/cache"
	"project05_web/src/global"
	"time"
)

func SendEmailValidate(em []string, myType int) (string, error) {
	e := email.NewEmail()
	e.From = fmt.Sprintf("1291034656@qq.com")
	e.To = em
	// 生成6位随机验证码
	driver := base64Captcha.NewDriverDigit(80, 240, 5, 0.7, 80)

	cp := base64Captcha.NewCaptcha(driver, cache.RedisStore{})

	id, _, anwser, err := cp.Generate()
	if err != nil {
		return "", err
	}
	ems := em[0]

	//为id添加验证码类型，1为注册，2为登录
	if myType == 1 {
		id = fmt.Sprintf("%s&amp%s", id, "emailtoregister")
	} else {
		id = fmt.Sprintf("%s&amp%s", id, "emailtologin")
	}
	
	cmd := global.RedisDb.Set(context.Background(), ems, id, 2*time.Minute)
	if cmd.Err() != nil {
		log.Fatal(cmd.Err())
		return "", cmd.Err()
	}
	//设置文件发送的内容
	content := fmt.Sprintf(`
	<div>
		<div>
			您好！
		</div>
		<div style="padding: 8px 40px 8px 50px;">
			<p>您提交的邮箱验证，本次验证码为<u><strong>%s</strong></u>，为了保证账号安全，验证码有效期为5分钟。请确认为本人操作，切勿向他人泄露，感谢您的理解与使用。</p>
		</div>
		<div>
			<p>此邮箱为系统邮箱，请勿回复。</p>
		</div>
	</div>
	`, anwser)
	e.Text = []byte(content)
	//设置服务器相关的配置
	err = e.Send("smtp.qq.com:25", smtp.PlainAuth("", "2242347682@qq.com", "ywdkgaiozzbzecce", "smtp.qq.com"))
	return anwser, err
}
